#pragma once
#include "LockGuard.hpp"
#include "thread.hpp"
#include<iostream>
#include <pthread.h>
#include<vector>
#include<queue>

const int g_thread_num=20;
template <class T>
class ThreadPool
{
public:
    pthread_mutex_t* getMutex(){
        return &_lock;
    }
    bool isEmpty(){
        return _task_queue.empty();
    }
    void WaitCond(){
        pthread_cond_wait(&_cond, &_lock);
    }
    T getTask(){
        T task=_task_queue.front();
        _task_queue.pop();
        return task;
    }
    static void* ThreadRoutine(void* args)
    {
        ThreadData* td=static_cast<ThreadData*>(args);
        ThreadPool<T>* tp=static_cast<ThreadPool<T>*>(args);
        while(true)
        {
            T task;
            {
                LockGuard lockguard(tp->getMutex());
                // LockGuard lockguard(&_mutex);
                // while(_task_queue.empty()){
                //     pthread_cond_wait(&_cond);
                // }
                // task=_task_queue.front();
                // _task_queue.pop();
            }
        }
    }
    static ThreadPool<T>* getThreadPool(int num=g_thread_num)
    {
        //这里会存在大量的申请锁并且释放锁的行为
        //为了避免资源过度的浪费所以嵌套两层判断
        if(thread_ptr==nullptr){
            LockGuard lockguard(&_mutex);
            if(thread_ptr){
                thread_ptr=new ThreadPool<T>(num);
            }
        }
        return thread_ptr;
    }
    void pushTask(const T task){
        LockGuard lockguard(&_lock);
        _task_queue.push(task);
        pthread_cond_signal(&_cond);
    }
    void run(){
        for(auto& iter:_threads){
            iter->Start();
        }
    }
    ~ThreadPool(){
        for(auto& iter:_threads){
            iter->Join();
            delete iter;
        }
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
private:
    ThreadPool(int thread_num=g_thread_num)
    :_num(thread_num)
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
        for(int i=0;i<_num;i++){
            _threads.push_back(new Thread(i,ThreadRoutine,this));
        }
    }
    ThreadPool(const ThreadPool<T>& )=delete;
    ThreadPool<T>& operator=(const ThreadPool<T>&)=delete;
    
    int _num;
    pthread_mutex_t _lock;
    pthread_cond_t _cond;
    std::vector<Thread*> _threads;
    std::queue<T> _task_queue;

    static ThreadPool<T>* thread_ptr;
    static pthread_mutex_t _mutex;
};
